package com.adui.mgt.performance.api;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.adui.mgt.performance.entity.User;
import com.adui.mgt.performance.metadata.req.SignReq;
import com.adui.mgt.performance.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


@RestController
@RequestMapping("/api/auth")
public class AuthApi {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public SaResult doLogin(@RequestBody SignReq signReq) {

        User user = userService.findUserByName(signReq.getUsername());
        if (Objects.isNull(user)) {
            return SaResult.error("用户不存在");
        }
        if (!StringUtils.equals(signReq.getPassword(), user.getPassword())) {
            return SaResult.error("密码错误");
        }
        StpUtil.login(user.getUsername());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return SaResult.data(tokenInfo);
    }

    @GetMapping("/login-status")
    public Boolean isLogin() {
        return StpUtil.isLogin();
    }

    @GetMapping("/logout")
    public void logOut() {
        StpUtil.logout();
    }
}
